package com.example.task;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.utils.CacheUtils;
import com.example.common.utils.HttpUtils;
import com.example.dao.TPlanRecordDetailMapper;
import com.example.model.entity.TPlan;
import com.example.model.entity.TPlanRecord;
import com.example.model.entity.TPlanRecordDetail;
import com.example.service.TEquipmentService;
import com.example.service.TPlanRecordService;
import com.example.service.TPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class keepConnectTask {

    @Value("${idispatch_addr:}")
    private String idispatch_addr;

    @Autowired
    private TPlanRecordService planRecordService;

    @Autowired
    private TEquipmentService equipmentService;

    @Autowired
    private TPlanService planService;

    @Autowired
    private TPlanRecordDetailMapper planRecordDetailMapper;

    @Scheduled(fixedRate = 15000)//15秒
    public void keepConnectTask() throws Exception {
        Object token = CacheUtils.get("myToken");
        if(token == null){
            return;
        }
        Map paramMap = new HashMap<>();
        JSONObject resultJson = HttpUtils.postAddHeader(idispatch_addr+"/keepconnect",paramMap);
//        JSONObject result = HttpUtils.httpRequest(idispatch_addr+"/keepconnect","","GET");
//        log.info("保活msg:"+resultJson);
        //{"msg":"fail","reason":"user_logout","status":400}
        if("fail".equals((String)resultJson.get("msg"))){
            CacheUtils.remove("myToken");
            return;
        }
        //轮询
        resultJson = HttpUtils.sendGet(idispatch_addr+"/poll","");
//        log.info("轮询msg1:"+resultJson);
        JSONArray msgJsonArray = resultJson.getJSONArray("msg");
        if (msgJsonArray.size() == 0 ) {
            return;
        }
        for(Object obj :msgJsonArray){
            JSONObject json = JSONUtil.parseObj(obj);
            String type = (String) json.get("type");
            String result = (String) json.get("result");
            String mesgId = (String) json.get("mesg_id");
            switch (type){
                case "BroadcastCall":
                    if(result.equals("fail")){
                        //重发广播
                        TPlanRecord record = planRecordService.getById(mesgId);
                        TPlan plan = planService.getById(record.getPlanId());
                        equipmentService.broadcast(plan,record.getWarningId());
                    }else if(result.equals("succ")){
                        updateRecordStatus(mesgId);
                    }else if(result.equals("try")){
                        //记录成员状态
                        JSONObject eventdataJson = (JSONObject) json.get("eventdata");
                        if(eventdataJson.isNull("calledResult") ||  eventdataJson.isNull("calledDevice")){
                            break;
                        }
                        String calledResult = (String) eventdataJson.get("calledResult");
                        String calledDevice = (String) eventdataJson.get("calledDevice");
                        Long status = calledResult.equals("succ")?1L:0L;
                        saveRecordDetail(mesgId,status,calledDevice);
                    }
                    break;
                case "SmsSend":
                    String smsid = (String) json.get("smsid");
                    if(result.equals("fail")){
                        //重发短信
                        TPlanRecord record = planRecordService.getById(mesgId);
                        TPlan plan = planService.getById(record.getPlanId());
                        equipmentService.sendSms(plan,record.getWarningId());
                    }else if(result.equals("succ")){
                        updateRecordStatus(mesgId);
                    }
                    String smsCallee = saveRecordDetailSms(smsid);
                    Long status = result.equals("succ")?1L:0L;
                    saveRecordDetail(mesgId,status,smsCallee);
                    break;
//                case "SmsStatus":
//                    String smsDirect = (String) json.get("smsDirect");
//                    if(smsDirect.equals("send")){
//                        String smsResult = (String) json.get("result");
//                        String smsTo = (String) json.get("smsTo");
//                        String smsIDRemark = (String) json.get("smsID");
//                        String[] to = smsTo.split("\\|");
//                        Long status = smsResult.equals("send succ")?1L:0L;
//                        saveRecordDetail(mesgId,status,to[0],smsIDRemark);
//                    }
//                    break;
                default:
            }
        }
    }

     void updateRecordStatus(String mesgId){
        QueryWrapper<TPlanRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TPlanRecord::getPlanRecordId,mesgId);
        TPlanRecord record = new TPlanRecord();
        record.setStatus(1L);
        record.setUpdateDate(LocalDateTime.now());
        planRecordService.update(record,queryWrapper);
    }

    void saveRecordDetail(String mesgId,Long calledResult ,String calledDevice){
        TPlanRecordDetail detail = new TPlanRecordDetail();
        detail.setPlanRecordId(mesgId);
        detail.setCreateDate(LocalDateTime.now());
        detail.setDetailObj(calledDevice);
        detail.setStatus(calledResult);
        planRecordDetailMapper.insert(detail);
    }

    void updateSmsPlanRecordDetail(String mesgId,String smsID){
        QueryWrapper<TPlanRecordDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TPlanRecordDetail::getIsValid,1L)
                .eq(TPlanRecordDetail::getRemarks,smsID);
        TPlanRecordDetail detail = new TPlanRecordDetail();
        detail.setPlanRecordId(mesgId);
        planRecordDetailMapper.update(detail,queryWrapper);
    }

    /*
    * 根据smsID获取号码
    *
    * */
    String saveRecordDetailSms(String smsid) throws Exception {
        Map map = new HashMap<>();
        map.put("smsid", smsid);
        JSONObject resultJson = HttpUtils.postAddHeader(idispatch_addr+"/smsrecord",map);
        JSONArray record_list =(JSONArray) resultJson.get("record_list");
        JSONObject record = (JSONObject) record_list.get(0);
        String smsCallee = (String) record.get("smsCallee");
        return smsCallee;
    }

}
